<?php
class PassportController extends AbstractController
{
    public function __init()
    {
//        if(!isset($_SESSION))
//        {
//            @session_start();
//        }
    }
    
	public function index()
	{
		$passportCls = new PassportModel();
		$uid = $passportCls->isLogined();
	    if(!$passportCls->isLogined())
	    	$this->view->setThemeFile('index/login.php');
	    else
	    {
	    	$this->view->assign('uid', $uid);
	    	$this->view->setThemeFile('index/index.php');
	    }
	    $this->view->display();
	}
	
	public function register()
	{
	    if($this->requstMethod == 'POST')
	    {
	    	$error = '';
	    	$passportCls = new PassportModel();
	        $username = Functions::sqlgpc('p_username', 'P', '');
	        $password = Functions::sqlgpc('p_password', 'P', '');
	        $password_r = Functions::sqlgpc('p_password_r', 'P', '');
	        if(empty($username) || empty($password) || empty($password_r) || !$passportCls->checkUserName($username) || $password_r != $password)
	        {
	            $error = '注册信息不符合要求！';
	        }
	        else 
	        {
		        $pwdInfo = $passportCls->getMd5Password($password);
		        $userInfo = array(
		            'UserName'=>$username,
		            'Password'=>$pwdInfo['md5Passwrod'],
		        	'Salt'=>$pwdInfo['salt'],
		        	'Status'=>1,
		        	'CreateDate'=>time(),
		            'Remark'=>'',
		        );
		        if($passportCls->addUser($userInfo))
		        {
		        	$this->_redirect('?m=passport');
		        }
		        else 
		        {
		        	$error = '系统错误，注册失败！';
		        }
	        }
	        $this->view->assign('Error', $error);
	    }
	    $this->view->setThemeFile('index/register.php');
	    $this->view->display();
	}
	
	
	
	/**
	 * 用户登陆
	 */
	public function login()
	{
	    
	    if($this->requstMethod == 'POST')
	    {
	    	$passPortCls = new PassportModel();
	    	$loginResult = array('loginAction' => false, 'success'=>false);
	    	$loginResult['success'] = $passPortCls->isLogined();
	    
	        $loginResult['loginAction'] = true;
	        $username = Functions::sqlgpc('p_username', 'P', '');
	        $password = Functions::sqlgpc('p_password', 'P', '');
	        $loginResult['success'] = $passPortCls->loginCheck($username, $password);
	        if($loginResult['success'])
		    {
		        $this->_redirect('?m=index');
		    }
		    $this->view->setThemeFile('index/login.php');
		    $this->view->assign('LoginResult', $loginResult);
	    }
	    $this->index();
	}
	
	public function logout()
	{
	    setcookie(Config::getConfig('COOKIEPRE', 'Passport').'uid', null);
    	setcookie(Config::getConfig('COOKIEPRE', 'Passport').'token', null);
	    $this->_redirect('?m=index');
	}
}